package com.graduate.emos.wx.aop;

import cn.hutool.core.util.StrUtil;
import com.graduate.emos.wx.common.util.R;
import com.graduate.emos.wx.config.shiro.ThreadLocalToken;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class TokenAspect {

    @Autowired
    private ThreadLocalToken threadLocalToken;

    //定义切点
    @Pointcut("execution(public * com.graduate.emos.wx.controller.*.*(..))")
    public void aspect(){}

    @Around("aspect()")//环绕事件用于拦截所有web方法的返回值，在返回的==R对象==中添加更新后的token令牌
    public Object around(ProceedingJoinPoint point) throws Throwable{
        //方法执行的结果
        R r = (R) point.proceed();
        //从媒介类中获取新的token
        String token = threadLocalToken.getToken();
        if (!StrUtil.isEmpty(token)){
            //如果获取的token不为空，说明是更新的token
            //将token放入响应的结果中
            r.put("token",token);
            //清空媒介类中的token
            threadLocalToken.clear();
        }
        return r;
    }
}
